<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="!dataForm.id ? $t('add') : $t('update')"
               :modal="false"
               class="user-dialog add-or-updata"
               width="50%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="100px">
        <div class="label-left-form">
          <div class="form-item-flex">
            <el-form-item prop="label"
                          :rules="stringRule(true,0,50)"
                          label="标签">
              <el-input v-model.trim="dataForm.label"
                        placeholder="支持多个 ; 分号隔开"></el-input>
            </el-form-item>
            <el-form-item prop="headline"
                          :rules="stringRule(true,0,100)"
                          label="标题">
              <el-input v-model.trim="dataForm.headline"
                        placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item prop="subheading"
                          :rules="stringRule(false,0,100)"
                          label="副标题">
              <el-input v-model.trim="dataForm.subheading"
                        placeholder="请输入副标题"></el-input>
            </el-form-item>
            <el-form-item prop="classify"
                      label="分类"
                      :rules="required()">
              <el-select v-model="dataForm.classify"
                        placeholder="请选择分类"
                        class="width-100">
                <el-option v-for="item in classificationOptions"
                          :key="item.dictValue"
                          :label="item.dictName"
                          :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="remark"
                          :rules="stringRule(false,0,100)"
                          label="备注">
              <el-input v-model.trim="dataForm.remark"
                        placeholder="请输入备注"></el-input>
            </el-form-item>
          </div>
          <div class="form-item-flex margin-left-20">
            <el-form-item prop="fileAddress"
                          label="附件">
              <file-upload ref="fileUpload"
                           @success="successLoad"
                           @remove="handleRemove" />
            </el-form-item>
          </div>
        </div>
        <div>
          <tinymce ref="tinymce"
                   :isEdit='!!dataForm.id' />
        </div>
      </el-form>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t('cancel')}}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t('confirm')}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import fileUpload from '@/components/file-upload/file-upload'
import tinymce from '@/components/tinymce/tinymce'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addURL: '/tb/information/addInformation', // 添加接口，API地址
        updateURL: '/tb/information/updateInformation', // 修改接口，API地址
        getDataInfoURL: '/tb/information/getInformation?id=', // 数据详情，API地址
        deleteURL: '/tb/file/delFileOss', // 文件删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      isSubmit: false,
      tempDeleteFileList: [], // 临时删除的文件
      newEditFileList: [], // 保存在编辑时新增的文件路径
      visible: false,
      classificationOptions: [{
        dictName: '政策新闻',
        dictValue: 0
      }, {
        dictName: '典型案例',
        dictValue: 1
      }, {
        dictName: '线上培训',
        dictValue: 2
      }],
      dataForm: {
        fileAddress: [],
        content: '',
        label: '',
        headline: '',
        subheading: '',
        remark: '',
        status: 0,
        picAddress: '',
        videoAddress: '',
        rests: []
      }
    }
  },
  components: { fileUpload, tinymce },
  methods: {
    closeDialog () {
      this.$refs.dataForm.resetFields()
      this.dataForm.content = ''

      // 在新增关闭时如果文件列表中还有文件就删除
      if (this.dataForm.rests.length && !this.dataForm.id) {
        const url = []
        this.dataForm.rests.map(item => {
          url.push(item.url)
        })
        this.deleteFile(url)
      }

      // 当提交完成后如果临时文件列表中还有文件就删除
      if (this.tempDeleteFileList.length && !this.isSubmit) {
        this.deleteFile(this.tempDeleteFileList)
      }

      this.$refs.tinymce.clear(this.isSubmit)
      this.dataForm.fileAddress = []
      this.tempDeleteFileList = []
      this.newEditFileList = []
      this.dataForm.picAddress = ''
      this.dataForm.videoAddress = ''
      this.dataForm.subheading = ''
      this.dataForm.status = 0
      this.dataForm.remark = ''
      this.dataForm.rests = []
      this.isSubmit = false
      this.visible = false
    },
    init (data) {
      this.visible = true

      if (this.dataForm.id) {
        this.getDataInfo().then(res => {
          if (res.code !== 0) {
            return
          }

          // 回显文件
          if (res.data.rests !== '' && res.data.rests !== null) {
            const temp = JSON.parse(res.data.rests)
            this.dataForm.rests = temp
            this.$refs.fileUpload.init(temp)
          } else {
            this.dataForm.rests = []
          }

          this.$refs.tinymce.init(res.data.content, res.data.picAddress, res.data.videoAddress)

          this.dataForm.fileAddress = res.data.fileAddress ? res.data.fileAddress.split(',') : []
        })
      }
    },
    // 文件上传成功
    successLoad (name, url) {
      this.dataForm.rests.push({
        name,
        url
      })
      this.dataForm.fileAddress.push(url)

      if (this.dataForm.id) {
        this.newEditFileList.push(url)
      }
    },
    // 监听是否删除文件
    handleRemove (file, index) {
      // 如果删除的文件为编辑时新添加的文件的话立即调用删除接口
      const item = this.newEditFileList.filter(item => item === file.url)
      if (item.length) {
        this.deleteFile([item[0]])
      }

      this.tempDeleteFileList.push(file.url)
      this.dataForm.rests.splice(index, 1)
      this.dataForm.fileAddress.splice(index, 1)
    },
    // 删除文件
    deleteFile (path) {
      this.getDataList({ url: this.mixinViewModuleOptions.deleteURL, paramData: { fileName: path.join(',') } })
        .then(res => {
          if (res.code !== 0) {
            return false
          }
          this.tempDeleteFileList = []
        })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const tinymce = this.$refs.tinymce
          const url = this.dataForm.id ? this.mixinViewModuleOptions.updateURL : this.mixinViewModuleOptions.addURL
          this.dataForm.content = tinymce.getContent()
          this.dataForm.picAddress = tinymce.getImagePath()
          this.dataForm.videoAddress = tinymce.getVideoPath()
          this.dataForm.rests = JSON.stringify(this.dataForm.rests)
          this.dataForm.fileAddress = this.dataForm.fileAddress.join(',')
          this.addOrUpdateItem({ url }).then(res => {
            if (res.code !== 0) {
              this.dataForm.fileAddress = this.dataForm.fileAddress ? this.dataForm.fileAddress.split(',') : []
              this.dataForm.rests = JSON.parse(this.dataForm.rests)
              return
            }
            this.isSubmit = true
            this.dataForm.rests = []
            this.$emit('callBack')
            this.closeDialog()
          })
        }
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss" scoped>
.label-left-form {
  display: flex;
  justify-content: space-between;
  .form-item-flex {
    flex: 1;
  }
}
</style>
